package cn.xyafu.lost.fragment;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.xyafu.lost.R;
import cn.xyafu.lost.activity.LostDetailActivity;
import cn.xyafu.lost.activity.MainActivity;
import cn.xyafu.lost.adapter.ListViewBodyAdapter;
import cn.xyafu.lost.pojo.Lost;
import cn.xyafu.lost.utils.Constant;
import cn.xyafu.lost.utils.ToastUtils;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HomeFragment extends BaseFragment {

    private static ObjectMapper mapper;
    private ListView listView; // 显示列表的listview
    private EditText search_et; // 搜索输入框
    private Button search_btn;  // 搜索按钮

    private int totalCount;// 数据总条数
    private int lastVisibleIndex;   //可见数据条数

    private List<Lost> losts;

    private int page = 1;

    private String keyWord = "";    // 搜索关键字

    private FragmentManager mFm;
    private Fragment mContent;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContext = getActivity();
        // inflater: 打气筒, 给fragment填充布局
        final View view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        initData();

        search_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 搜索功能
                page = 1;
                keyWord = search_et.getText().toString().trim();
                initData();
                if (keyWord.equals("")){
                    FragmentManager fragmentManager = getFragmentManager(); // 获取Fragment管理器
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.content_layout,new HomeFragment());// 替换
                    fragmentTransaction.commit();//提交
                }
            }
        });
        return view;
    }

    // 初始化view
    private void initView(View view) {
        search_et = view.findViewById(R.id.search_et);
        listView = view.findViewById(R.id.listView);
        search_btn = view.findViewById(R.id.search_btn);
    }

    /**
     * 申请指定的权限.
     */
    public void requestPermission(int code, String... permissions) {

        if (Build.VERSION.SDK_INT >= 23) {
            requestPermissions(permissions, code);
        }
    }

    /**
     * 判断是否有指定的权限
     */
    public boolean hasPermission(String... permissions) {

        for (String permisson : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(), permisson)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case Constant.HARDWEAR_CAMERA_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                }
                break;
            case Constant.WRITE_READ_EXTERNAL_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    doWriteSDCard();
                }
                break;
        }
    }

    // 发起网络请求
    private void initData() {
        //  发起网络请求
        // (1). 创建OkHttpCLient对象
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        OkHttpClient client = builder.build();
        // (2). 创建Request对象
        Request request = new Request.Builder().url("http://localhost/Lost_ssm/android/findAll?page=" + page + "&keyWord=" + keyWord).get().build();
        // (3). 创建Call对象
        Call call = client.newCall(request);
        // (4). 将请求添加到队列中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("请求成功");
                // 1. 将json数据转化为model数据
                String jsonString = response.body().string();
                losts = JSON.parseArray(jsonString,Lost.class);

                // 2 更新界面
                search_et.post(new Runnable() { // 由于在子线程中,需要通过post来更新界面
                    @Override
                    public void run() {
                        // 3. 将数据传递给适配器,然后将适配器适配给listview
                        updateList();
                    }
                });

            }
        });
    }

    private void updateList(){
        final ListViewBodyAdapter bodyAdapter = new ListViewBodyAdapter(getActivity(),losts);
        listView.setAdapter(bodyAdapter);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

                // 获取更多数据，添加到adapter
                if (scrollState == 1
                        && lastVisibleIndex == bodyAdapter.getCount()) {
                    loadMoreData();// 加载更多数据
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // 计算最后可见条目的索引
                lastVisibleIndex = firstVisibleItem + visibleItemCount;
                // 当adapter中的所有条目数已经和要加载的数据总条数相等时，则移除底部的View
                if (totalItemCount == totalCount + 1) {

                }

            }
        });

        setItemClickListener(listView);

    }

    private boolean flag = true;

    private void loadMoreData() {

        if (!flag){
            return ;
        }

        page++;

        //  发起网络请求
        // (1). 创建OkHttpCLient对象
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        OkHttpClient client = builder.build();
        // (2). 创建Request对象
        Request request = new Request.Builder().url("http://localhost/Lost_ssm/android/findAll?page=" + page + "&keyWord=" + keyWord).get().build();
        // (3). 创建Call对象
        Call call = client.newCall(request);
        // (4). 将请求添加到队列中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("请求成功");

                // 1. 将json数据转化为model数据
                String jsonString = response.body().string();
                //添加到list中
                List<Lost> newLosts = JSON.parseArray(jsonString, Lost.class);
                if (newLosts.size() > 0){
                    losts.addAll(newLosts);
                    // 重新加载daapter
                    search_et.post(new Runnable() {
                        @Override
                        public void run() {

                            int i = losts.size();

                            listView.setAdapter(new ListViewBodyAdapter(getActivity(),losts));
                            System.out.println(losts.size());
                            listView.setSelection(i-6);//刷新完后调转到第一条内容处
                        }
                    });
                }else{
                    page--;
                    flag = false;
                }

            }
        });
    }

    // listView 设置点击事件
    private void setItemClickListener(ListView listView){

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = view.findViewById(R.id.item_lid_view);
                String lid = textView.getText().toString().trim();
                Intent intent = new Intent(mContext, LostDetailActivity.class);
                intent.putExtra("lid",lid);
                startActivityForResult(intent,2);
            }
        });

    }



}